package com.ruoyi.mp.service.impl;


import com.ruoyi.common.core.constant.UserConstants;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.EncryptAesUtil;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.redis.service.RedisService;
import com.ruoyi.db.domain.system.MpClient;
import com.ruoyi.db.domain.system.MpClientFriends;
import com.ruoyi.db.domain.system.PcTeamConfig;
import com.ruoyi.db.domain.system.dto.MpClientFriendCount;
import com.ruoyi.db.domain.web.dto.MpRegistForm;
import com.ruoyi.db.mapper.system.MpClientFriendsMapper;
import com.ruoyi.db.mapper.system.MpClientMapper;
import com.ruoyi.db.mapper.system.PcTeamConfigMapper;
import com.ruoyi.mp.service.IMpClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 【商城用户】Service业务层处理
 *
 * @author ruoyi
 * @date 2022-07-22
 */
@Service
@Transactional(rollbackOn = Exception.class)
public class MpClientServiceImpl implements IMpClientService
{
    @Autowired
    private MpClientMapper mpClientMapper;
    @Autowired
    private MpClientFriendsMapper mpClientFriendsMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private PcTeamConfigMapper pcTeamConfigMapper;

    /**
     * 查询【商城用户】
     *
     * @param clientId 【商城用户】主键
     * @return 【商城用户】
     */
    @Override
    public MpClient selectMpClientByClientId(Long clientId)
    {

        return mpClientMapper.selectMpClientByClientId(clientId);
    }

    /**
     * 查询【商城用户】列表
     *
     * @param mpClient 【商城用户】
     * @return 【商城用户】
     */
    @Override
    public List<MpClient> selectMpClientList(MpClient mpClient)
    {
        return mpClientMapper.selectMpClientList(mpClient);
    }

    /**
     * 修改【商城用户】
     *
     * @param mpClient 【商城用户】
     * @return 结果
     */
    @Override
    public int updateMpClient(MpClient mpClient)
    {
        return mpClientMapper.updateMpClient(mpClient);
    }

    @Override
    public void updPayPassword(MpRegistForm form,MpClient client) {
        String payPwd = form.getPassword();
        if (StringUtils.isNotBlank(payPwd))
        {
            Pattern p = Pattern.compile("\\d{6}");
            Matcher m = p.matcher(payPwd);
            if (payPwd.length()!=UserConstants.PAY_PASSWORD_LENGTH||!m.matches())
            {
                throw new ServiceException("交易密码长度必须为6位纯数字");
            }
            String rPwd = form.getrPassword();
            if(StringUtils.isBlank(rPwd)||!payPwd.equals(rPwd)){
                throw new ServiceException("两次密码不一致");
            }
            String code = form.getCode();
            if(StringUtils.isBlank(code)){
                throw new ServiceException("验证码不能为空");
            }
            if(!redisService.hasKey("PAY"+client.getMobile())||!redisService.getCacheObject("PAY"+client.getMobile()).toString()
                    .equals(code)){
                throw new ServiceException("验证码错误");
            }
            String entryPwd = EncryptAesUtil.encrypt(payPwd);
            client.setPayPassword(entryPwd);
            mpClientMapper.updateMpClient(client);
        }else{
            throw new ServiceException("请输入交易密码");
        }
    }

    @Override
    public void updPassword(MpRegistForm form, MpClient client) {
        String password = form.getPassword();
        //密码验证
        if (StringUtils.isBlank(password)){
            throw new ServiceException("密码不能为空");
        }
        if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
                || password.length() > UserConstants.PASSWORD_MAX_LENGTH)
        {
            throw new ServiceException("密码长度必须在5到20个字符之间");
        }
        String rPwd = form.getrPassword();
        if(StringUtils.isBlank(rPwd)||!password.equals(rPwd)){
            throw new ServiceException("两次密码不一致");
        }
        //验证码验证
        String code = form.getCode();
        if(StringUtils.isBlank(code)){
            throw new ServiceException("验证码不能为空");
        }
        if(!redisService.hasKey("UPDP"+client.getMobile())||!redisService.getCacheObject("UPDP"+client.getMobile()).toString()
                .equals(code)){
            throw new ServiceException("验证码错误");
        }
        String entryPwd = EncryptAesUtil.encrypt(password);
        client.setPassword(entryPwd);
        mpClientMapper.updateMpClient(client);
    }

    @Override
    public void updMobile(MpRegistForm form, MpClient client) {
        String mobile = form.getMobile();
        //密码验证
        if (StringUtils.isBlank(mobile)){
            throw new ServiceException("手机号不能为空");
        }
        Pattern p = Pattern.compile("^1[3-9]\\d{9}$");
        Matcher m = p.matcher(mobile);
        if(!m.matches()){
            throw new ServiceException("手机号格式不正确");
        }
        MpClient sMpClient = new MpClient();
        sMpClient.setMobile(mobile);
        List<MpClient> sList = mpClientMapper.selectMpClientList(sMpClient);
        if(sList.size()>0){
            throw new ServiceException("手机号已注册");
        }
        //验证码验证
        String code = form.getCode();
        if(StringUtils.isBlank(code)){
            throw new ServiceException("验证码不能为空");
        }
        if(!redisService.hasKey("UPDM"+client.getMobile())||!redisService.getCacheObject("UPDM"+client.getMobile()).toString()
                .equals(code)){
            throw new ServiceException("验证码错误");
        }
        client.setMobile(mobile);
        mpClientMapper.updateMpClient(client);
    }

    @Override
    public MpClient selectMpClientAndParentByClientId(MpClient client) {
        MpClientFriends friends = new MpClientFriends();
        friends.setClienId(client.getClientId());
        List<MpClientFriends> list = mpClientFriendsMapper.selectMpClientFriendsList(friends);
        if(list!=null&&list.size()!=0){
            MpClient parent = mpClientMapper.selectMpClientByClientId(list.get(0).getpClientId());
            client.setInviteName(parent.getName());
        }
        if(client.getTeamConfigId()!=null){
            PcTeamConfig configs = pcTeamConfigMapper.selectPcTeamConfigById(client.getTeamConfigId());
            if(configs!=null){
                client.setTeamLevel(configs.getTeamLevel());
            }else{
                client.setTeamLevel("普通会员");
            }
        }else{
          client.setTeamLevel("普通会员");
        }
        if(client.getIsVirtual()!=null&&client.getIsVirtual()==2){
            client.setTeamLevel("事业部");
        }
        return client;
    }

    //递归出所有用户下级id
    private List<Long> getUserIds(List<MpClientFriends> userIdlist){
        List<Long> ids = new ArrayList<>();
        if(userIdlist!=null && userIdlist.size()>0){
            for(MpClientFriends vo:userIdlist){
                ids.add(vo.getClienId());
                MpClientFriends parentF = new MpClientFriends();
                parentF.setpClientId(vo.getClienId());
                List<MpClientFriends> childs =mpClientFriendsMapper.selectMpClientFriendsList(parentF);
                ids.addAll(getUserIds(childs));
            }
        }
        return ids;
    }

}
